const router = require('express').Router()
const User = require('./db/userSchema.js')
const Battery = require('./db/batterySchema.js')
const Contract = require('./db/contractSchema.js')
const PowerStation = require('./db/powerStationSchema.js')

const Conversation = require('./db/conversationSchema.js')
const LeaveWord = require('./db/leaveWordSchema.js')

const multer = require('multer')
const { checkToken } = require('./jwt')

// 图片上传
const storageInfo = multer.diskStorage({
  destination: 'imgs/',
  filename(req, file, cb) {
    cb(null, `${req.query.id}.png`)
  }
})
const upload = multer({ storage: storageInfo })
router.post('/upload', upload.array('file'), (req, res) => {
  res.send('已添加')
})
// 用户管理
router.get('/users', async (req, res) => {
  const data = await User.find()
  res.send({ flag: true, data, msg: '查询成功' });
})
router.post('/updUser', async (req, res) => {
  console.log(req.body);
  const { _id, ...data } = req.body
  const result = await User.updateMany(
    { _id },
    { $set: data }
  )
  res.send({ flag: true, data: result, msg: '修改成功' });
})
router.get('/delUser', async (req, res) => {
  const data = await User.deleteMany(req.query)
  res.send({ flag: true, data, msg: '删除成功' });
})
// 电池管理
router.get('/get-battery-list', async (req, res) => {
  const data = await Battery.find(req.query)
  res.send({ flag: true, data, msg: '查询成功' });
})
router.post('/updBattery', async (req, res) => {
  console.log(req.body);
  const { _id, ...data } = req.body
  const result = await Battery.updateMany(
    { _id },
    { $set: data }
  )
  res.send({ flag: true, data: result, msg: '修改成功' });
})
router.get('/delBattery', async (req, res) => {
  const data = await Battery.deleteMany(req.query)
  res.send({ flag: true, data, msg: '删除成功' });
})
// 租赁合同(含聚合查询)
router.get('/delContract', async (req, res) => {
  const data = await Contract.deleteMany(req.query)
  res.send({ flag: true, data, msg: '删除成功' });
})
const aggregateQuery = () => {
  return Contract.aggregate([
    {
      $lookup: {             // 1. 关联用户集合，获取用户信息
        from: "users",       // 需要关联的集合
        localField: "customerId",// 总表的ID标识字段
        foreignField: "name",// 关联表的ID标识字段
        as: "usersList"      // 输出数组字段名
      }
    },
    // {
    //   $unwind: "$usersList", // 2. 展开用户信息（会过滤掉用户为空的数据）
    // },
    {
      $lookup: { // 3. 关联电池集合，获取电池信息
        from: "batterys",
        localField: "batteryId",
        foreignField: "batteryId",
        as: "contractsList"
      }
    },
    {
      $project: { // 5. 返回需要的字段
        contractId: 1,
        customerId: "$usersList.nick",
        batteryId: "$contractsList.model",
        startDate: 1,
        endDate: 1,
        rentalFee: 1,
        paymentStatus: 1,
        contractType: 1,
        paymentMethod: 1,
        deposit: 1,
        lateFeeRate: 1,
        renewalTimes: 1,
        terminationReason: 1,
        signDate: 1,
      }
    }
  ])
}
router.get('/get-contract-list', async (req, res) => {
  const data = await aggregateQuery()
  res.send({ flag: true, data, msg: '查询成功' });
})
//电站管理
router.get('/get-powerStation-list', async (req, res) => {
  const data = await PowerStation.find(req.query)
  res.send({ flag: true, data, msg: '查询成功' });
})
//会话中心
router.get('/get-conversation-list', async (req, res) => {
  const data = await Conversation.find(req.query)
  res.send({ flag: true, data, msg: '查询成功' });
})
router.get('/del-conversation-list', async (req, res) => {
  const data = await Conversation.deleteMany(req.query)
  console.log(data);
  res.send({ flag: true, data: [], msg: '会话已清空' });
})
router.get('/get-leaveword-list', async (req, res) => {
  const data = await LeaveWord.find({ account: req.query.account })
  res.send({ flag: true, data, msg: '查询成功' });
})
router.post('/add-leaveword', checkToken, async (req, res) => {
  const data = await new LeaveWord({ time: new Date().getTime(), ...req.body }).save()
  res.send({ flag: true, data, msg: '查询成功' });
})
router.post('/del-leaveword', async (req, res) => {
  const data = await LeaveWord.deleteMany({ ...req.body })
  res.send({ flag: true, data, msg: '查询成功' });
})
module.exports = router